<template>
    <div class="ScreenViewManageList">
        <div class="ScreenViewManageList-le">
            <a-tabs v-model:activeKey="activeKey" size="small" style="height: 100%">
                <a-tab-pane key="dashboard">
                    <template #tab>
                        <span><profile-outlined/>{{ i18n('list.dashboard', '仪表板') }}</span>
                    </template>
                    <div style="display: flex;flex-direction: column;height: calc(100% - 60px)">
                        <div style="padding: 0px 10px 10px 10px">
                            <a-input v-model:value="params.Q_NAME__S_LK" @pressEnter="init"
                                     :placeholder="i18n('msa.searchContent','请输入搜索内容')"/>
                            <div class="instrument">
                                <div class="instrument-name">{{ i18n('list.dashboard', '仪表板') }}</div>
                                <template v-if="parenData.length>0">
                                    <div style="color: #4285f4;cursor: pointer;margin-right: 10px;"
                                         @click.stop="exportScreens">
                                        <rx-icon-show icon="icon-linea-exportdata"></rx-icon-show>
                                        {{ $ti18('rxList.exportBtn', '导出') }}
                                    </div>
                                    <div style="color: #4285f4;cursor: pointer" @click.stop="design('-1')">
                                        <rx-icon-show icon="icon-lineVue3_add"></rx-icon-show>
                                        {{ $ti18('rxList.newBtn', '新建') }}
                                    </div>
                                </template>
                            </div>
                        </div>
                        <div class="ScreenViewManageList-le-tree">
                            <screenViewManageTree ref="tree" @initTree="initTree" @design="design" @delById="delById"
                                                  @screenTree="screenTree" @allInit="init"
                                                  :selectView="selectView" :parenData="parenData"
                                                  :treeData="treeData"></screenViewManageTree>
                        </div>
                    </div>
                </a-tab-pane>
                <a-tab-pane key="collect">
                    <template #tab>
                        <span><rx-icon-show icon="icon-linestar-collection"/>{{ i18n('list.collect', '收藏') }}</span>
                    </template>
                    <screen-collect-record-list
                        @screenTree="screenTree"
                        @delCollectTree="delCollectTree"
                        :key="dragKey"
                        :selectView="selectView"
                        :largeList="largeList"
                        :appId="appId"
                    ></screen-collect-record-list>
                </a-tab-pane>
                <a-tab-pane key="share">
                    <template #tab>
                        <span><share-alt-outlined/>{{ i18n('list.share', '分享') }}</span>
                    </template>
                    <screen-share-list
                        @screenTree="screenTree"
                        :key="dragKey"
                        :selectView="selectView"
                        :largeList="largeList"
                        :appId="appId"
                    ></screen-share-list>
                </a-tab-pane>
            </a-tabs>
        </div>
        <div class="ScreenViewManage-content" v-show="selectView.id">
            <div class="ScreenViewManage-content-head">
                <div>
                    <span class="ScreenViewManage-content-span">{{ $i18(selectView.name) }}</span>
                    <span class="ScreenViewManage-conten-text">	{{ $ti18('rxForm.createBy', '创建人') }}：{{
                            selectView.createByName
                        }}
						<a-popover>
							<template #content>
								<div class="a-tooltip-title">
									<div style="font-weight: bold;">{{ $ti18('rxForm.createBy', '创建人') }}</div>
									<div class="a-tooltip-name">{{ selectView.createByName }}</div>
									<div style="font-weight: bold;">{{ $ti18('rxForm.createTime', '创建时间') }}</div>
									<div class="a-tooltip-name">{{ selectView.createTime }}</div>
									<div style="font-weight: bold;">{{ i18n('list.recentReviser', '最近修改人') }}</div>
									<div class="a-tooltip-name">{{ selectView.updateByName }}</div>
									<div style="font-weight: bold;">{{ i18n('list.lastRevision', '最近修改时间') }}</div>
									<div class="a-tooltip-name">{{ selectView.updateTime }}</div>
								</div>
							</template>
							<info-circle-outlined/>
						</a-popover>
						<rx-icon-show v-if="!selectView.isCollect" style="margin-left: 5px;font-size: 16px"
                                      icon="icon-linestar-collection" :title="i18n('list.collect','收藏')"
                                      @click="collectView(selectView.isCollect)"/>
						<rx-icon-show v-else style="margin-left: 5px;font-size: 16px;color:#fadb14 "
                                      icon="icon-fillstar-collection-fill" :title="i18n('list.uncollect','取消收藏')"
                                      @click="collectView(selectView.isCollect)"/>
				</span>
                </div>
                <div class="ScreenViewManage-head">
                    <div @click="isMobile=false" class="ScreenViewManageEdit-button"
                         :class="{'ScreenViewManageEdit-button-hover':!isMobile}">
                        <rx-icon-show icon="icon-fillcomputer_fill"></rx-icon-show>
                        {{ designI18n('index.computerLayout', '电脑端布局') }}
                    </div>
                    <div @click="isMobile=true" class="ScreenViewManageEdit-button"
                         :class="{'ScreenViewManageEdit-button-hover':isMobile}">
                        <rx-icon-show icon="icon-fillmobilephone_fill"></rx-icon-show>
                        {{ designI18n('index.mobileLayout', '移动端布局') }}
                    </div>
                </div>
                <div class="ScreenViewManage-conten-button">
                    <a-button v-if="selectView.createBy==curUser.userId" type="primary" @click="design(selectView.id)">
                        {{ $ti18('rxList.editBtn', '编辑') }}
                    </a-button>
                    <a-button @click="preview(selectView.alias)">
                        <template #icon>
                            <fullscreen-outlined/>
                        </template>
                        {{ i18n('list.fullPreview', '全屏预览') }}
                    </a-button>
                    <a-dropdown>
                        <a-button> {{ $ti18('rxList.moreBtn', '更多') }}</a-button>
                        <template #overlay>
                            <a-menu style="min-width: 150px">
                                <a-menu-item key="1">
                                    <div class="a-menu-item-common" @click="deployMenu(selectView)">
                                        <rx-icon-show icon="icon-lineVue3_publish"></rx-icon-show>
                                        {{ i18n('form.deployMenu', '发布菜单') }}
                                    </div>
                                </a-menu-item>
                                <a-menu-item key="2">
                                    <div class="a-menu-item-common" @click="exportImage">
                                        <rx-icon-show icon="icon-linecloud-download"></rx-icon-show>
                                        {{ i18n('form.exportImage', '导出图片') }}
                                    </div>
                                </a-menu-item>
                                <a-menu-item key="3">
                                    <div class="a-menu-item-common" @click="exportScreen">
                                        <rx-icon-show icon="icon-linea-exportdata"></rx-icon-show>
                                        {{ $ti18('rxList.exportBtn', '导出') }}
                                    </div>
                                </a-menu-item>
                                <a-menu-item key="4">
                                    <div class="a-menu-item-common" v-if="selectView.createBy==curUser.userId"
                                         @click="share">
                                        <rx-icon-show icon="icon-lineVue3_share"></rx-icon-show>
                                        {{ designI18n('index.share', '分享') }}
                                    </div>
                                </a-menu-item>
                                <a-menu-item key="6">
                                    <div class="a-menu-item-common" @click="getMobileLink">
                                        <tablet-outlined/>
                                        {{ designI18n('index.mobileLink', '移动端链接') }}
                                    </div>
                                </a-menu-item>
                                <a-menu-item key="5" v-if="selectView.createBy==curUser.userId">
                                    <div class="a-menu-item-common" type="danger" ghost @click="delById(selectView.id)">
                                        <rx-icon-show icon="icon-lineVue3_delete"></rx-icon-show>
                                        {{ $ti18('rxList.delBtn', '删除') }}
                                    </div>
                                </a-menu-item>
                            </a-menu>
                        </template>
                    </a-dropdown>
                </div>
            </div>
            <div class="ScreenViewManage-content-right" id="ScreenViewManageId">
                <screenPreview :isMobile="isMobile" :key="dragKey" v-if="selectView && selectView.alias" :alias="selectView.alias"
                               :width="scrollWidth"></screenPreview>
            </div>
        </div>
        <div class="rx-loading" v-if="loading">
            <a-spin />
        </div>
        <div class="ScreenViewManage-content-blank" v-else-if="!selectView.id">
            <div><img style="width: 400px;margin-top: 130px" src="@img/blank.png"/></div>
            <div class="content-blank-name">
                {{ i18n('msa.createData', '当前无数据，先从新建目录开始，赶紧创建属于你的仪表盘吧') }}
            </div>
            <a-button @click="onAddTree" style="margin-top: 30px" type="primary">
                <plus-outlined/>
                {{ i18n('list.newDirectory', '新建目录') }}
            </a-button>
        </div>
    </div>
</template>

<script>
import ScreenViewManageApi from '@/api/screen/core/screen-view-manage.js'
import {Util} from '@lowcode/jpaas-base-lib';
import SysMenuAddNode from "./sys-menu-add-node.vue";
import ScreenApi from "@/api/screen-api";
import screenPreview from "@/views/modules/preview/index.vue"
import screenViewManageTree from "@/views/modules/screen/core/screen-view-manage-tree.vue"
import screenViewManageTreeDialog from "@/views/modules/screen/dialog/screen-view-manage-tree-dialog.vue"
import html2canvas from "html2canvas";
import ScreenShare from "@/views/modules/screen/dialog/screen-share.vue";
import ScreenCollectRecordList from "./screen-collect-record-list.vue";
import ScreenCollectRecordApi from '@/api/screen/core/screen-collect-record'
import ScreenShareList from './screen-share-list.vue'
import {mapState} from 'pinia';
import useMain from "../../../../stores/use-main";

export default {
    name: 'ScreenViewManageList',
    computed: {
        ...mapState(useMain, ['user', "token", "appId"])
    },
    components: {
        screenPreview,
        screenViewManageTree,
        ScreenCollectRecordList,
        ScreenShareList,
    },
    data() {
        return {
            activeKey: "dashboard",
            fitSearch: false,
            selectView: {},
            largeList: [],
            dragKey: new Date().getTime(),
            scrollWidth: '',
            params: {
                Q_NAME__S_LK: '',
            },
            treeData: [],
            parenData: [],
            isMobile: false,
            serverAddress: "",
            curUser: {},
            loading:true,
        }
    },
    created() {
        this.init(true);
        this.getServerAddress();
    },
    mounted() {
        let freedomDiv = document.getElementById('ScreenViewManageId');
        if (freedomDiv) {
            this.scrollWidth = freedomDiv.scrollWidth;
        } else {
            this.scrollWidth = document.documentElement.clientWidth
        }
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "screenLang", key);
        },
        designI18n(name, text, key) {
            return this.$ti18(name, text, "designLang", key);
        },
        getById(id){
            ScreenViewManageApi.get(id).then(res=>{
                this.selectView = res.data ? res.data:"";
                this.dragKey = new Date().getTime();
            });
        },
        screenTree(obj) {
            this.getById(obj.pkId);
        },
        delCollectTree() {
            this.init();
            this.selectView = "";
            this.dragKey = new Date().getTime();
        },
        initTree() {
            let params = {
                catKey: 'SCREEN',
                readKey: 'read',
                isAdmin: true,
                isGrant: true,
                appId: this.appId || '',
            };
            ScreenApi.getByCatKey(params).then(res => {
                this.loading = false
                this.parenData = res;
                let ary = Util.listToTree(this.reconsitution(res), "treeId", "parentId");
                this.treeData = ary;
                this.treeData.forEach(res=>{
                    if(res.list && res.list.length>0){
                        this.getById(res.list[0].pkId);
                    }
                })
            })
        },
        init() {
            let appId = this.appId;
            if (appId) {
                this.params.Q_APP_ID__S_EQ = appId;
            }
            ScreenApi.getScreenViewManageList(this.params).then(res => {
                if (res.success) {
                    this.largeList = res.data;
                    this.initTree()
                }
            })
        },
        reconsitution(type) {
            let list = type.filter(res => {
                res.name = this.$i18(res.name, '分类名称');
                res['list'] = [];
                this.largeList.filter(obj => {
                    if (res.treeId == obj.categoryId) {
                        res['list'].push(obj)
                    }
                })
                return res
            })
            return list
        },
        delById(ids) {
            let self = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                content: this.i18n("msa.delViewMsa", "您确定要删除当前视图吗?"),
                zIndex: 40000,
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                    ScreenViewManageApi.del({ids: ids}).then(() => {
                        self.init();
                        self.selectView = "";
                    })
                }
            })
        },
        getListByParams(parameter) {
            return ScreenViewManageApi.query(parameter)
        },
        design(pkId) {
            if (!this.treeData || this.treeData.length==0){
                this.$message.warning(this.i18n("msa.createDir","请先创建目录"));
                return
            }
            let item={
                path: "/design/" + pkId
            }
            if(this.appId){
                item["query"]={
                    appId: this.appId
                }
            }
            let url=this.$router.resolve(item).href;
            window.open(url,"window_" + pkId);
        },
        preview(alias) {
            let url = "/screen/preview/" + alias;
            if(this.appId){
              url += "?appId="+this.appId;
            }
            window.open(url, '_blank');
        },
        deployMenu(record) {
            let conf = {
                curVm: this,
                component: SysMenuAddNode,
                title: this.i18n('form.deployMenu', '发布菜单'),
                widthHeight: ['600px', '600px'],
                data: {
                    record: record
                },
                zIndex: 999,
            }
            Util.open(conf, function (action) {
                if (action != 'ok') return;
            })
        },
        categoryChange(id) {
            this.categoryId = id
            this.init()
        },
        refresh() {

        },
        onAddTree() {
            this.$refs.tree.onAddTree();
        },
        exportImage() {
            this.isHtml2canvas();
        },
        isHtml2canvas() {
            let scrollHeight = document.getElementById('ScreenViewManageId').scrollHeight;
            html2canvas(document.getElementById("ScreenViewManageId"), {
                backgroundColor: '#ececec', //画布背景色（如果未在DOM中指定）。设置null为透明
                allowTaint: true,
                useCORS: true,
                scale: 2, // 处理模糊问题
                dpi: 350, // 处理模糊问题
                height: scrollHeight,
                windowHeight: scrollHeight,
            }).then((canvas) => {
                let canvasImg = canvas.toDataURL("image/png", 1);
                //调用下载方法
                this.downLoadFile(this.selectView.name, canvasImg);
            });
        },
        downLoadFile(fileName, canvasImg) {
            //创建一个a标签
            let a = document.createElement("a");
            //指定下载文件名称
            a.href = canvasImg;
            a.download = fileName;
            //模拟点击
            a.click();
        },
        //导出
        exportScreen() {
            if (!this.selectView || !this.selectView.pkId) {
                this.$message.warning(this.i18n("msa.exportTips", "请先设计大屏再导出!"));
                return;
            }
            //导出
            ScreenViewManageApi.exportScreenByIds([this.selectView.pkId]);
        },
        //导出多个
        exportScreens() {
            let conf = {
                curVm: this,
                component: screenViewManageTreeDialog,
                title: this.i18n('list.screenExport', '大屏导出'),
                widthHeight: ['600px', '600px'],
                data: {
                    showCheckBtn: true,
                    treeData: this.treeData,
                    selectView: this.selectView,
                    parenData: this.parenData
                },
                zIndex: 999,
            }
            Util.open(conf, function (action, data) {
                if (action != 'ok') return;
                ScreenViewManageApi.exportScreenByIds(data);
            })
        },
        share() {
            let conf = {
                curVm: this,
                component: ScreenShare,
                title: this.designI18n("index.sharePage", "页面分享配置"),
                widthHeight: ['1000px', '600px'],
                data: {
                    alias: this.selectView.alias
                },
                zIndex: 999,
            };
            Util.open(conf, function (action) {
                if (action != 'ok') return;
            });
        },
        collectView(isCollect) {
            if (!this.selectView.pkId) {
                return;
            }
            if (isCollect) {
                ScreenCollectRecordApi.unCollect(this.selectView.pkId).then(res => {
                    if (!res.success) {
                        return;
                    }
                    this.selectView.isCollect = false;
                    this.init();
                    this.dragKey = new Date().getTime();
                });
            } else {
                ScreenCollectRecordApi.addCollect(this.selectView.pkId).then(res => {
                    if (!res.success) {
                        return;
                    }
                    this.selectView.isCollect = true;
                    this.init();
                    this.dragKey = new Date().getTime();
                });
            }
        },
        getServerAddress() {
            ScreenApi.getServerAddress().then(res => {
                if (res) {
                    this.serverAddress = res.serverAddress;
                    this.curUser = res.currentUser;
                }
            });
        },
        getMobileLink() {
            let mobileUrl = this.serverAddress + "/screen/mobile/" + this.selectView.alias;
            if(this.appId){
              mobileUrl += "?appId="+this.appId;
            }
            let tag = document.createElement('input');
            tag.setAttribute('id', 'copyInput');
            tag.value = mobileUrl;
            document.getElementsByTagName('body')[0].appendChild(tag);
            document.getElementById('copyInput').select();
            document.execCommand('copy');
            document.getElementById('copyInput').remove();
            this.$message.success("复制成功!");
        }
    }
}
</script>
<style scoped>
.a-menu-item-common i {
    margin-right: 5px;
}

.a-menu-item-common:hover {
    color: rgb(66, 133, 244);
}

.ScreenViewManageList-le >>> .ant-tabs-nav-list {
    margin-left: 10px!important;
}
.ScreenViewManageList-le>>>.ant-tabs-content{
    height: 100%;
}

.ScreenViewManageList-le >>> .ant-tabs .ant-tabs-small-bar .ant-tabs-tab {
    padding: 8px 10px !important;
}

.ScreenViewManageEdit-button-hover {
    background-color: #4285f4;
    color: white;
    border-radius: 4px;
}

.ScreenViewManageEdit-button:hover {
    background-color: #4285f4;
    color: white;
    border-radius: 4px;
}

.ScreenViewManageEdit-button {
    display: flex;
    padding: 0px 10px;
    height: 32px;
    font-size: 14px;
    justify-content: center;
    align-items: center;
    line-height: 32px;
    cursor: pointer;
    border-radius: 4px;
    border: solid 1px #dadde0;
}

.ScreenViewManageEdit-button:nth-child(1) {
    margin-right: 37px;
}

.ScreenViewManageEdit-button i {
    margin-right: 12px;
}

.ScreenViewManage-head {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
}

.button-more {
    display: flex;
    flex-direction: column;
    width: 200px;
}

.content-blank-name {
    font-size: 16px;
    color: #cccccc;
}

.ScreenViewManage-content-blank {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.a-tooltip-title {
    padding-right: 50px;
}

.a-tooltip-name {
    font-size: 12px;
    color: #555555;
    margin-bottom: 10px;
}

.instrument {
    display: flex;
    height: 30px;
    line-height: 30px;
    align-items: center;
    margin-top: 10px;
}

.instrument-name {
    flex: 1;
    font-size: 14px;
    font-weight: bold;
}

.ScreenViewManage-content-right {
    flex: 1;
    overflow: hidden;
    position: relative;
}

.ScreenViewManage-content {
    flex: 1;
    flex-direction: column;
    display: flex;
}

.ScreenViewManage-conten-button button {
    margin-left: 10px;
}

.ScreenViewManage-content-head {
    height: 60px;
    display: flex;
    padding: 0px 20px;
    width: 100%;
    align-items: center;
}

.ScreenViewManage-content-span {
    font-size: 16px;
    color: #333333;
}

.ScreenViewManage-conten-text {
    height: 12px;
    color: #666666;
    line-height: 12px;
    font-size: 12px;
    border-left: 1px solid #e8e8e8;
    margin-left: 15px;
    padding-left: 16px;
    flex: 1;
}

.ScreenViewManageList {
    display: flex;
    width: 100%;
    height: 100%;
}

.ScreenViewManageList-le {
    width: 260px;
    height: 100%;
    overflow: hidden;
    border-right: 1px solid #e8e8e8;
    display: flex;
    flex-direction: column;
}

.ScreenViewManageList-le-tree {
    overflow-y: auto;
    overflow-x: clip;
    flex: 1;
}
.ScreenViewManageList-le-tree>>>.ant-collapse-content-box{
    padding: 0px!important;
}
.rx-loading{
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    inset:0;
    z-index: 99999;
    background-color: rgba(0,0,0,.15);
}
</style>

